var mongoose = require('mongoose'),
	crypto = require('crypto'),
	UserSchema = new mongoose.Schema({
		idChat : { type: Number, default: '' },
		username:  { type: String, default: '' },
		password: { type: String, default: '' },
		name: { type: String, default: '' },
		salt: { type: String, default: '' },
  		authToken: { type: String, default: '' },
  		timeCreate: {type: Number, default: ''},
  		listSocketId : {type : Array, default: []}
	});

UserSchema.methods = {
	AddSocketId : function(_id, newSocketId, callback){
		// this.model('User').findByIdAndUpdate(_id,
		// 						{$push: { listSocketId: newSocketId}},
		// 						function(err, doc){
		// 							if(callback !== undefined){
		// 								callback();
		// 							}
		// 						});

		this.model('User')
				.findById(_id,
					'listSocketId',
					function(err,doc){
						if (err || !doc) {
							console.log(err,doc);
						}else{
							var index = doc.listSocketId ? doc.listSocketId.indexOf(newSocketId) : -1;
							if(index == -1){
								doc.listSocketId.push(newSocketId);
								doc.save(function(error) {
									if (error) {
										console.log('loi luu',error);
									} else {
										// send the records
									}
									if(callback !== undefined){
										callback();
									}
								});
							}else{
								if(callback !== undefined){
									callback();
								}
							}
						}
					});
	},

	RemoveSocketId : function(_id, socketId, callback){
		this.model('User')
				.findById(_id,
					'listSocketId',
					function(err,doc){
						if (err || !doc) {
							console.log(err, doc);
						} else {
							var index = doc.listSocketId ? doc.listSocketId.indexOf(socketId) : -1;
							if(index !== -1){
								doc.listSocketId.splice(index, 1);
								doc.save(function(error) {
									if (error) {
										console.log('loi xoa',error);
									} else {
										// send the records
									}
									if(callback !== undefined){
										callback();
									}
								});
							}
						}
					});
	},

	GetSocketId : function(idChat, callback){
		this.model('User')
				.find({idChat : idChat},
					'listSocketId',
					function(err, doc){
						var _return = [];
						if (err || !doc) {
							console.log(err, doc);
						} else {
							_return = doc.listSocketId;
						}
						callback();
					});
	},

	Login : function(username, password, callback){
		this.model('User').find({'username': username, 'password': password},
							function(err, docs){
								var _return = false;
								if(err || !docs){

								}else{
									_return = true;
								}
								if(callback) callback(_return);
							});
	},

	Register : function(username, password, callback){
		var _this = this
		this.model('User').find({'username': username}, function(err, docs){
			var _return = false;
				console.log(err, docs);

			if(docs.length == 0){
				var date = new Date(),
					components = [
					    date.getYear(),
					    date.getMonth(),
					    date.getDate(),
					    date.getHours(),
					    date.getMinutes(),
					    date.getSeconds(),
					    date.getMilliseconds(),
					    Math.round(Math.random()*10),
					    Math.round(Math.random()*10),
					    Math.round(Math.random()*10)
					];
				_this.model('User').create({
			        idChat : components.join(""),
			        username : username,
			        salt : _this.makeSalt(),
			        password : _this.encryptPassword(password),
			        timeCreate : (new Date().valueOf())
			    },function (err, doc) {
			    	console.log(err, doc);
					if (err || !doc) {
						console.log(err);
						if(callback) callback(false, err, docs);
					}else{
						if(callback) callback(true, err, doc);
					}
				});
			}else{
				if(callback) callback(false, err, docs);
			}
		});
	},

	Authorization : function(username, password, callback){
		var _this = this;
		var query = this.model('User').findOne({'username': username, 'password': _this.encryptPassword(password)});
		query.exec(function (err, doc) {
			callback(err, doc);
		});
	},

	AuthorizationNoEncrypt: function(username, password, callback){
		var _this = this;
		var query = this.model('User').findOne({'username': username, 'password': password});
		query.exec(function (err, doc) {
			callback(err, doc);
		});
	},

	/**
	* Authenticate - check if the passwords are the same
	*
	* @param {String} plainText
	* @return {Boolean}
	* @api public
	*/

	authenticate : function (plainText) {
	    return this.encryptPassword(plainText) === this.password;
	},



	/**
	* Make salt
	*
	* @return {String}
	* @api public
	*/

	makeSalt : function () {
	    return Math.round((new Date().valueOf() * Math.random())) + '';
	},

	/**
	* Encrypt password
	*
	* @param {String} password
	* @return {String}
	* @api public
	*/

	encryptPassword : function (password) {
		if (!password) return '';
	    var encrypred;
	    try {
	      encrypred = crypto.createHmac('sha1', this.salt).update(password).digest('hex')
	      return encrypred;
	    } catch (err) {
	      return '';
	    }
	}
}

module.exports = mongoose.model('User', UserSchema);